package com.example.petadopt.ui.activity;

import android.os.Bundle;
import android.view.MenuItem;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;

import com.example.petadopt.R;
import com.example.petadopt.ui.fragment.DiscoverFragment;
import com.example.petadopt.ui.fragment.HomeFragment;
import com.example.petadopt.ui.fragment.ProfileFragment;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.navigation.NavigationBarView;

public class MainActivity extends AppCompatActivity {

    private BottomNavigationView bottomNavigationView;
    private Fragment homeFragment, discoverFragment, profileFragment;
    private Fragment activeFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();
        initListener();
        setupFragments();
    }

    private void initView() {
        bottomNavigationView = findViewById(R.id.bottom_navigation);
    }

    private void initListener() {
        bottomNavigationView.setOnItemSelectedListener(new NavigationBarView.OnItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                int itemId = item.getItemId();
                if (itemId == R.id.nav_home) {
                    switchFragment(homeFragment);
                    return true;
                } else if (itemId == R.id.nav_discover) {
                    switchFragment(discoverFragment);
                    return true;
                } else if (itemId == R.id.nav_profile) {
                    switchFragment(profileFragment);
                    return true;
                }
                return false;
            }
        });
    }

    private void setupFragments() {
        // 初始化各个Fragment
        homeFragment = new HomeFragment();
        discoverFragment = new DiscoverFragment();
        profileFragment = new ProfileFragment();

        // 设置默认显示的Fragment为首页
        getSupportFragmentManager().beginTransaction()
                .add(R.id.fragment_container, homeFragment)
                .add(R.id.fragment_container, discoverFragment).hide(discoverFragment)
                .add(R.id.fragment_container, profileFragment).hide(profileFragment)
                .commit();

        activeFragment = homeFragment;
    }

    private void switchFragment(Fragment targetFragment) {
        if (activeFragment != targetFragment) {
            getSupportFragmentManager().beginTransaction()
                    .hide(activeFragment)
                    .show(targetFragment)
                    .commit();
            activeFragment = targetFragment;
        }
    }
}